package svc.elib.db;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

import svc.elib.util.FastRAFReader;

/**
 * Corrects names of authors
 * 
 * @author svc
 * @date 5.6.2013
 */
public class NameCorrector {

	private HashMap<String, String> lookup = 
		new HashMap<String, String>();
	
	private boolean foundError = false;
	
	public NameCorrector() 
		throws IOException
	{
		Properties prop = new Properties();
		prop.put("FileToRead", "nameLookup.csv");
		prop.put("BufferSize", String.valueOf(1024 * 16));
		prop.put("MaxLineLength", String.valueOf(1024 * 16));
		prop.put("MaxFields", "64");
		prop.put("TextEncoding", "UTF-8");
		prop.put("FieldSeparator", ";");
		
		FastRAFReader frf = new FastRAFReader(prop);
		int lineNo = 1;
		while(-1 != frf.nextLine()) {
			String firstName = frf.getFieldAsSBR(0).toString().trim();
			String lastName = frf.getFieldAsSBR(1).toString().trim();
			String correctedFirstName = frf.getFieldAsSBR(2).toString().trim();
			String correctedLastName = frf.getFieldAsSBR(3).toString().trim();
			
			String authorName = lastName + "_" + firstName;
			if (lookup.containsKey(authorName)) {
				System.out.println("NameLookupError, duplicated name " + authorName + ", line no: " + lineNo);
				foundError = true;
			}
			
			lookup.put(authorName, correctedLastName + "_" + correctedFirstName);
			++lineNo;
		}
		frf.close();
		
		foundError = checkLookup();
	}
	
	public boolean hasToBeCorrected(String firstName, String lastName) {
		return lookup.containsKey(lastName + "_" + firstName);
	}
	
	public String getCorrection(String firstName, String lastName) {
		return lookup.get(lastName + "_" + firstName);
	}
	
	public void dumpLookup() {
		System.out.println("Name correction lookup:");
		Set<Entry<String, String>> es = lookup.entrySet();
		Iterator<Entry<String, String>> it = es.iterator();
		while (it.hasNext()) {
			Entry<String, String> e = it.next();
			System.out.println(e.getKey() + " --> " + e.getValue());
		}
		
		System.out.println("\n--------------------------------");
		if (lookupOK()) {
			System.out.println("Consistent lookup");
		} else {
			System.out.println("WARNING: Inconsistent lookup");
		}
	}
	
	public boolean checkLookup() {
		boolean err = false;
		Set<Entry<String, String>> es = lookup.entrySet();
		Iterator<Entry<String, String>> it = es.iterator();
		while (it.hasNext()) {
			Entry<String, String> e = it.next();
			String replacement = e.getValue();
			if (lookup.containsKey(replacement)) {
				System.out.println("Name lookup error: " + replacement + " both key and value");
				err = true;
			}
		}
		
		return err;
	}
			
	
	public boolean lookupOK() {
		return !foundError;
	}
	
	public static void main(String[] args) 
		throws IOException
	{
		NameCorrector nc = new NameCorrector();
		nc.dumpLookup();
	}
}
